
const formidable = require("formidable");
const util = require('../utils/util');
const config = require("../config")
const fs = require('fs')
const path = require('path')

// 文件相关请求独自处理

async function upload(request, response) {
    var form = new formidable.IncomingForm();
    form.uploadDir = "./images";
    form.parse(request, function (e, fields, files) {
        if (e) {
            response.writeHead(500, {
                "Content-Type": "text/html"
            });
            response.write(e.message);
            response.end();
            console.error("Unexpected Error: ", e);
        } else {
            let suffix = path.extname(files.file.originalFilename)
            var new_name = util.randname() + suffix;

            fs.renameSync(files.file.filepath, "./images/" + new_name);
            response.writeHead(200, {
                "Content-Type": "text/html"
            });
            response.write(`${config.server}:${config.port}/images/${new_name}`);
            response.end();
        }
    });
}

async function view_image(pathname, response) {
    fs.readFile('.' + pathname, "binary", function(e, file) {
        if(e) {
            response.writeHead(500, { "Content-Type": "text/plain" });
            response.write(e.message);
            response.end();
            console.error("Unexpected Error: ", e);
        } else {
            response.writeHead(200, {"Content-Type": "image/png"});
            response.write(file, "binary");
            response.end();
        }
    });
}

module.exports = {
    upload: upload,
    view_image: view_image,
}
